package com.imast.android.bys.ui;

import org.ksoap2.serialization.SoapPrimitive;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.imast.android.bys.R;
import com.imast.android.bys.task.SoapPrimitiveTaskFragment.TaskCallbacks;
import com.imast.android.bys.util.SessionManager;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

public class SplashActivity extends ActionBarActivity {
	
	private PlaceholderFragment placeFragment;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.activity_splash);
		if (savedInstanceState == null) {
			placeFragment = new PlaceholderFragment();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		} 
		else {
			placeFragment = (PlaceholderFragment) getSupportFragmentManager().findFragmentById(R.id.container);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.splash, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//if (requestCode == SplashHelper.RC_SIGN_IN) { 
			PlaceholderFragment fragment = (PlaceholderFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.container);
            fragment.onActivityResult(requestCode, resultCode, data);
		//}
		/*else {
			super.onActivityResult(requestCode, resultCode, data);
		}*/
			
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment implements TaskCallbacks {
		
		SplashHelper helper;
		
		private Session.StatusCallback callback = new Session.StatusCallback() {
		    @Override
		    public void call(Session session, SessionState state, Exception exception) {
		        helper.onSessionStateChange(session, state, exception);
		    }
		};
		
		private UiLifecycleHelper uiHelper;

		public PlaceholderFragment() {}
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			
			uiHelper = new UiLifecycleHelper(getActivity(), callback);
			uiHelper.onCreate(savedInstanceState);
			
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_splash,
					container, false);
			
			helper = new SplashHelper(this, getActivity(), rootView, uiHelper);
			
			return rootView;
		}
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			helper.onActivityCreated(this);
			
		}
		
		@Override
		public void onStart() {
			super.onStart();
			helper.getGoogleApiClient().connect();
		}
		
		@Override
		public void onResume() {
			super.onResume();
			
			// For scenarios where the main activity is launched and user
		    // session is not null, the session state change notification
		    // may not be triggered. Trigger it if it's open/closed.
		    Session session = Session.getActiveSession();
		    if (session != null &&
		           (session.isOpened() || session.isClosed()) ) {
		        helper.onSessionStateChange(session, session.getState(), null);
		    }
			
			helper.getUiHelper().onResume();
		}
		
		@Override
		public void onPause() {
			super.onPause();
			helper.getUiHelper().onPause();
		}
		
		@Override
		public void onStop() {
			super.onStop();
			if (helper.getGoogleApiClient().isConnected()) {
				helper.getGoogleApiClient().disconnect();
	        }
		}
		
		@Override
		public void onDestroy() {
			super.onDestroy();
			helper.getUiHelper().onDestroy();
		}
		
		@Override
		public void onSaveInstanceState(Bundle outState) {
			super.onSaveInstanceState(outState);
			helper.getUiHelper().onSaveInstanceState(outState);
		}
		
		@Override
		public void onActivityResult(int requestCode, int resultCode,
				Intent data) {
			if (requestCode == SplashHelper.RC_SIGN_IN) { 
		        if (resultCode != RESULT_OK) { 
		            helper.setSignInClicked(false); 
		        } 
		        
		        Intent intent = new Intent(getActivity(), MainActivity.class);
		        startActivity(intent);
		        helper.setIntentInProgress(false); 
		  
		        if (!helper.getGoogleApiClient().isConnecting()) { 
		        	helper.getGoogleApiClient().connect(); 
		        } 
		    }
			else {
				super.onActivityResult(requestCode, resultCode, data);
				helper.getUiHelper().onActivityResult(requestCode, resultCode, data);
			}
		}

		@Override
		public void onPreExecute() {
			helper.showDialog();
		}

		@Override
		public void onProgressUpdate(int percent) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onCancelled() {
			helper.hidePDialog();
			
		}

		@Override
		public void onPostExecute(SoapPrimitive soapPrimitive) {			
			if (Boolean.valueOf(soapPrimitive.toString())){
				helper.hidePDialog();
				
				helper.getSession().createLoginSession("demo","demo", "demo@gmail.com", SessionManager.BYS_LOGIN, null, null);
	            
				Intent intent = new Intent(getActivity(), MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			} else {
				Toast.makeText(getActivity().getApplicationContext(), R.string.toastLoginError, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
